package com.situ.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.controller.User;

import javafx.collections.ListChangeListener.Change;

@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("LoginFilter.init()");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		if ("/login.jsp".equals(servletPath) 
				|| "/login".equals(servletPath)) {
			chain.doFilter(request, response);
		} else {
			HttpSession session = httpServletRequest.getSession();
			User user = (User) session.getAttribute("user");
			if (user == null) {
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
				return;
			}
			// 如果已经登录要放行
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {
		System.out.println("LoginFilter.destroy()");
	}

}
